// app.js
import * as Apis from '/apis/index'
import { webUrl,testToken,version,debug } from '/config'
import {base64Encode,base64Decode} from "/utils/base64";
const whitePath = ['/pages/index/index']
App({
  async onLaunch(options) {
    let path = options && options.path ? '/'+options.path:'/pages/index/index'

    this.globalData.appOptions = Object.assign({},this.globalData.appOptions || {},{path},options.query || {})
    console.log('options',this.globalData.appOptions)
    if(!whitePath.includes(path)){
      await this.initApp()
    }
    // this.getAddedStatus()
  },
  globalData: {
    appOptions:{
      appId: wx.getAccountInfoSync().miniProgram.appId
    },
    payInfo:{},
    isAdded:false,
    isIphoneX:false,
    userInfo: null,
  },
  async checkToken () {
    const {token} = this.globalData.userInfo || {}
    if(!token){
      await this.initToken()
    }
    return this.globalData.userInfo || {}
  },
  initToken () {
    return new Promise((resolve, rejects) => {
      try {
        wx.login({
          success:async (res)=> {
            if (res.code) {
              const { appId } = this.globalData.appOptions
              const {data:checkRes}= await Apis.getAppCode({
                appId,
                code:res.code
              })
              const uToken={ token:checkRes && checkRes.Authorization?checkRes.Authorization : '' }
              const userInfo = await this.getUserInfo(uToken)
              console.log('userInfo',userInfo)
              resolve(userInfo)
            }else{
              this.showToast('登录失败！' + res.errMsg)
            }
          }
        })
      } catch (error) {
        rejects()
      }
    })
  },
  async getUserInfo(data = undefined){
    let userInfo = Object.assign({},this.globalData.userInfo || {},wx.getStorageSync('rechargeUser') || {},data || {})
    this.globalData.userInfo = userInfo
    // if(userInfo.token){
    //   const { data:res }= await Apis.uUserInfo({})
    //   const res = {}
    //   userInfo= Object.assign({}, {
    //     token:res && res.user ? userInfo.token : '',
    //     roles:res?.roles || []
    //   })
    //   this.globalData.userInfo = userInfo
    // }
    wx.setStorageSync('rechargeUser', userInfo)
    return userInfo || {}
  },
  async initApp(){    
    try {
      const { token } = await this.initToken()
      console.log('token',token)
      if(token){
         const options = this.globalData.appOptions || {}
         let url = options && options.path ? options.path:'/pages/index/index'
         if(url.indexOf('/')!==0){
          url = url + '/'
         }
         const query = this.globalData.appOptions || {}
         Object.keys(query || {}).map((key)=>{
           if(query[key]){
             url = url +(String(url).includes('?')?'&':'?')
             url = url + key
             url = url + '='
             url = url + query[key]
           }
         })
         wx.redirectTo({ url })
       }else{
         wx.redirectTo({ url: '/pages/login/index' })
       }
    } catch (error) {
     console.log('授权失败',error)
    }
  },
  getWebUrl(url){
    const uInfo = this.globalData.userInfo || {};
    if(webUrl && webUrl.includes(':8888/#') && !uInfo.token){
      uInfo.token = testToken
    }
    if(url){
      url = decodeURIComponent(url)
    }else{
      url = '/home/view'
    }
    url = url + (url.indexOf('?')!=-1?'&':'?') +'platform=wxApplet&appId='+this.globalData.appOptions.appId
    if(debug){
      url = url + '&debug=true'
    }
    if(version){
      url = url +  '&appVersion='+ version
    }
    if(uInfo.token){
      url = url +  '&token='+uInfo.token
    }
    const allParams = this.getParamsByUrl(url)
    this.globalData.appOptions = Object.assign({},this.globalData.appOptions || {},allParams || {})
    console.log('getWebUrl',this.globalData.appOptions)
    return url
  },
  getParamsByUrl (url){
    const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, '')
    if (!search) {
      return {}
    }
    const obj = {}
    const searchArr = search.split('&')
    searchArr.forEach(v => {
      const index = v.indexOf('=')
      if (index !== -1) {
        const name = v.substring(0, index)
        const val = v.substring(index + 1, v.length)
        obj[name] = val
      }
    })
    return obj
  },
  // 校验收藏
  checkIsAddedToMyMiniProgram() {
    return new Promise((resolve) => {
      try {
          wx.checkIsAddedToMyMiniProgram({
            success: (res) => { resolve({success:true,added:res.added}) },
            fail: (err) => { resolve({success:false,added:false,errMsg:err.errMsg})},
          });
      } catch (error) {
        resolve({success:false,added:false,errMsg:error.errMsg})
        console.log('error: ', error);
      }
    })
},
  getAddedStatus(){
    if (!wx.canIUse('checkIsAddedToMyMiniProgram')) {
      this.showError('暂无不支持查询添加状态,请升级微信')
      return false
    }
    let intervalTime
    let times = 0
    const cfun = async () => {
      times++
      const res = await this.checkIsAddedToMyMiniProgram()
      if(!res.success){
        if(intervalTime){
          clearInterval(intervalTime)
          intervalTime= null 
        }
        this.showToast(res.errMsg)
        return false
      }
      this.globalData.isAdded = res.added
      if(this.globalData.isAdded){
        if(intervalTime){
          clearInterval(intervalTime)
          intervalTime= null 
        }
        if(times>1){
          Apis.goCollection()
        }
      }
      if(times<=1){
        Apis.saveStartCollectionStatus({
          sc:this.globalData.isAdded?1:0
        })
      }
    }
    intervalTime = setInterval(()=>{
      cfun()
    },2000)
    cfun()
  },
  // 显示成功提示框
  showSuccess(msg, callback) {
    wx.showToast({
      title: msg,
      icon: 'success',
      success() {
        callback && callback();
      }
    });
  },
  //显示失败提示框
  showError(msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success(res) {
        callback && callback(res);
      }
    });
  },
  showToast(text,icon){
   wx.showToast({
     icon: icon?icon:"none",
     title:text?text:'',
     duration:1500
   });
  }
 
})
